<style src="./index.scss" lang="scss" scoped></style>
<template>
    <header class="base-layout-header-box">
        <div class="blh__bar">
            <!--            <div class="blh__bar-user-box">
                <div class="blh__bar-user-info">
                    <div class="blh__bar-user-logo">
                        <img src="~@/assets/avatar.png" alt="avatar">
                    </div>
                     <div class="blh__bar-user-detail">
                        <div class="blh__bar-user-detail-text">{{ (user && (user.username || user.realName)) || "哦豁，名字不见了"}}</div>
                        <div class="blh__bar-user-detail-tag">{{ (user && (user.position))}}</div>
                    </div>
                </div>
            </div>-->
            <div class="blh__bar-left">
                <div class="blh__bar-title">
                    乡村资源管理交易平台
                    <template v-if="currentArea">
                        <img src="~@/assets/map-location02.png" alt="" class="map-location">
                           {{currentArea}}
                    </template>
                </div>
            </div>
            <div class="blh__bar-btn blh__bar-right">
                <div class="blh__bar-btn-box">
                    <el-popover placement="bottom-start" trigger="hover">
                        <div class="contact-content">
                            <span>客服服务电话：400-8618-890</span>
                        </div>
                        <div slot="reference" class="contact">
                            <img
                                class="success"
                                src="~@/assets/icon-contact.png"
                                alt=""
                            />
                            <span class="contact-word">联系我们</span>
                        </div>
                    </el-popover>
                    <el-popover
                        placement="bottom"
                        width="210"
                        trigger="hover"
                        :disabled="isNormal"
                    >
                        <div>
                            您有新的消息，请<el-link @click="showList"
                                >前往</el-link
                            >查看
                        </div>
                        <el-link
                            slot="reference"
                            class="message"
                            @click="showList"
                        >
                            <el-badge
                                :value="messageNumber"
                                :max="99"
                                :hidden="!messageNumber"
                                class="message-item"
                            >
                                <img
                                    src="~@/assets/no-message.png"
                                    alt=""
                                    v-if="isNormal"
                                />
                                <img
                                    src="~@/assets/message-bell.gif"
                                    alt=""
                                    v-else
                                    class="message-bell"
                                />
                            </el-badge>
                            <span class="message-word">消息</span>
                        </el-link>
                    </el-popover>
                    <!-- <el-link icon="el-icon-edit" @click="toChangePassword">修改密码</el-link>
                    <span class="blh__bar-btn-step">|</span> -->
                    <el-dropdown @command="handleDropdownClick">
                        <div class="blh__bar-user-info">
                            <div class="blh__bar-user-text">
                                <el-link v-if="user.orgCategoryId === '7' || user.orgCategoryId === '6'">
                                    {{ user && user.departmentName ? user.departmentName + "-" : "" }}{{(user && (user.name || user.username)) || "哦豁，名字不见了" }}{{ user && user.position ? "(" + user.position + ")" : "" }}
                                </el-link>
                                <el-link v-else>
                                    {{(user && (user.name || user.username)) || "哦豁，名字不见了" }}
                                </el-link>
                            </div>
                            <i
                                class="blh__bar-user-text el-icon-arrow-down el-icon--right"
                            ></i>
                        </div>
                        <el-dropdown-menu
                            slot="dropdown"
                            class="header-dropdown"
                        >
                            <el-dropdown-item
                                icon="el-icon-edit"
                                command="password"
                            >
                                修改密码
                            </el-dropdown-item>
                            <el-dropdown-item
                                icon="iconfont icon-untie"
                                command="untie"
                                v-if="isBindWechat"
                            >
                                解绑微信
                            </el-dropdown-item>
                            <el-dropdown-item
                                icon="el-icon-link"
                                command="bind"
                                v-else
                            >
                                绑定微信
                            </el-dropdown-item>
                            <el-dropdown-item
                                icon="el-icon-switch-button"
                                command="logout"
                            >
                                退出登录
                            </el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                </div>
            </div>
        </div>
    </header>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import { State } from "vuex-class";
import { showToDoList } from "@/components/public/to-do-list/index";

@Component
export default class BaseLayoutHeader extends Vue {
    @State(state => state.user.userInfo) user: any;
    get currentArea() {
        const _current: any = this.currentAreaList;
        return _current && _current.id !== "0" ? _current.label.replace(/\//g, '-') || "" : "";
    }

    get currentAreaList() {
        const _current: any = this.authHistoryList[
            this.authHistoryList.length - 1
        ];
        return _current || {};
    }

    get authHistoryList() {
        const authHistory: any = this.$store.getters.getAuthHistory;
        return (authHistory && authHistory.list) || [];
    }


    created() {
        this.handleBindWechat();


        if (this.currentAreaList.label) {
            this.$store.dispatch("updateAuthArea", {
                id: this.currentAreaList.id,
                replace: true
            });
        }
        this.createWebSocket();
    }

    messageNumber = 0;
    ws: any = null;
    toDoList: any = [];
    show = false;
    isNormal = true;
    isBindWechat = false
    createWebSocket() {
        const url = this.$wsUrl + this.user.id;
        this.ws = new WebSocket(url);
        this.ws.onmessage = this.websocketOnMessage; // WebSocket通知
        this.ws.onopen = this.websocketOnOpen;
        this.ws.onerror = this.websocketOnError; // WebSocket异常
        this.ws.onclose = this.websocketClose; // WebSocket关闭
        // setTimeout(() => { this.overTime(this.ws); }, 1000 * 60 * 10);// 10分钟二维码登录过期
        window.onbeforeunload = () => {
            this.overTime(this.ws);
        };
    }

    websocketOnOpen(e: any) {
        console.log("建立连接");
        if (e.data && e.data !== "[]") {
            this.isNormal = false;
            this.toDoList = JSON.parse(e.data);
            if (this.show) {
                this.showList();
            }
        }
    }

    // 关闭ws
    overTime(ws: WebSocket) {
        console.log("主动关闭websocket========");
        if (ws) ws.close();
    }

    // 接受消息
    websocketOnMessage(e: any) {
        console.log("收到消息");
        if (e.data && e.data !== "[]") {
            this.isNormal = false;
            this.toDoList = JSON.parse(e.data);
            if (this.show) {
                this.showList();
            }
        }
    }

    // 连接建立失败重连
    websocketOnError() {
        setTimeout(() => {
            this.createWebSocket();
        }, 1000 * 3);
    }

    // 关闭连接
    websocketClose() {
        this.ws = null;
    }

    handleDropdownClick(command: any) {
        if (command === "logout") {
            this.logout();
        }
        if (command === "password") {
            this.toChangePassword();
        }
        if (command === "untie") {
            this.wechatUntie();
        }
        if (command === "bind") {
            this.wechatBind();
        }
    }

    async logout() {
        this.$confirm("真的要离开了吗?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
        })
            .then(async() => {
                await this.$store.dispatch("logout");
                this.$nextTick(() => {
                    this.$router.replace({ path: "/auth/login" });
                });
            })
            .catch();
    }

    toChangePassword() {
        this.$router.push({ path: "/user/home" });
    }

    // 查看待办事项
    showList() {
        this.show = true;
        this.isNormal = true;
        showToDoList({
            toDoList: this.toDoList,
            isTown: this.user.orgCategoryId === '7',
            close: () => {
                this.show = false;
            },
            toDoThings: (vm: any, model: any) => {
                let url = '';
                let reload: any = () => {
                    window.location.href = window.location.href.split('?')[0];
                    window.location.reload();
                };
                // 镇
                if (this.user.orgCategoryId === '7') {
                    url = '/module-manage/town-received';
                    reload = (tabs?: string): void => {
                        if (tabs) {
                            window.location.href = window.location.href.split('?')[0] + `?tabs=${tabs}`;
                        } else {
                            window.location.href = window.location.href.split('?')[0];
                        }
                        window.location.reload();
                    };
                }
                // 村
                if (this.user.orgCategoryId === '9') {
                    url = '/module-manage/village-collection-task';
                }
                switch (model.type) {
                case 1:
                    // 填报
                    if (this.checkUrl(url)) {
                        this.$router.push({ path: url, query: { tabs: '2' } });
                    } else {
                        reload(2);
                    }
                    break;
                case 2:
                    // 审批结果
                    if (this.checkUrl(url)) {
                        this.$router.push({ path: url });
                    } else {
                        reload();
                    }
                    break;
                case 3:
                    // 审核表单项
                    if (this.checkUrl("/resource-manage/user-add")) {
                        this.$router.push({ path: "/resource-manage/user-add" });
                    } else {
                        window.location.reload();
                    }
                    break;
                case 4:
                    // 审批表单
                    if (this.checkUrl("/module-manage/town-received")) {
                        this.$router.push({ path: "/module-manage/town-received" });
                    } else {
                        reload();
                    }
                    break;
                case 5:
                    // 数据分享
                    if (this.checkUrl("/module-manage/town-share-data")) {
                        this.$router.push({ path: "/module-manage/town-share-data" });
                    } else {
                        window.location.reload();
                    }
                    break;
                case 7:
                    // 转交
                    if (this.checkUrl(url)) {
                        this.$router.push({ path: url, query: { tabs: '2' } });
                    } else {
                        reload(2);
                    }
                    break;
                case 8:
                    // 抄送
                    if (this.checkUrl(url)) {
                        this.$router.push({ path: url, query: { tabs: '2' } });
                    } else if (this.$route.query.tabs !== '2') {
                        window.location.href = window.location.href + `?tabs=2`;
                        window.location.reload();
                    } else {
                        window.location.reload();
                    }
                    break;
                }
                vm.close();
            }
        });
    }

    checkUrl(url: any) {
        if (url === this.$route.path) {
            return false;
        }
        return url;
    }

    async wechatUntie() {
        this.$confirm("是否确定当前账号与微信解绑，解绑后可再次进行绑定", "解绑微信", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
        })
            .then(async() => {
                const res = await this.$server["user/unchainBind"]();
                if (res.status === 200 && res.data.code === 200) {
                    this.$message.success("解绑成功");
                    try {
                        const userInfo: any = JSON.parse(localStorage.userInfo);
                        userInfo.userThirdVoList.map((item: any) => {
                            if (item.type === 1) {
                                item.userThirdInfos.forEach((data: any, index: number) => {
                                    if (data.type === 2) {
                                        item.userThirdInfos.splice(index, 1, null);
                                    }
                                });
                            }
                        });
                        localStorage.setItem('userInfo', JSON.stringify(userInfo));
                        this.handleBindWechat();
                    } catch (e) {
                        console.log(e);
                    }
                } else {
                    this.$message.error((res.data ? res.data.message : res.message) ||
                        "接口请求错误!");
                }
            })
            .catch();
    }

    async wechatBind() {
        this.$loading({
            lock: true,
            text: 'Loading'
        });
        await this.$store.dispatch("logout");
        const rs = await this.$server["user/wxOpen"]();
        window.location.href = rs.data.data;
    }

    beforeDestroy() {
        this.overTime(this.ws);
    }


    handleBindWechat() {
        const userInfo: any = JSON.parse(localStorage.userInfo);
        let isBindWechat = false;
        try {
            if (!userInfo || !userInfo.userThirdVoList || userInfo.userThirdVoList.length === 0) {
                isBindWechat = false;
            }
            isBindWechat = userInfo.userThirdVoList.some((item: any) => {
                if (item.type === 1 && item.userThirdInfos && item.userThirdInfos.length !== 0) {
                    return item.userThirdInfos.some((data: any) => data.type === 2);
                } else {
                    return false;
                }
            });
        } catch (e) {
            console.log(e);
            isBindWechat = false;
        }
        this.isBindWechat = isBindWechat;
    }
}
</script>

<style scoped lang="scss">
.blh__bar-title{
    .map-location{
        width: 15px;
        position: relative;
        top: -3px;
    }
}
</style>
